import { login } from '@/api/user'

function getUser() {
  if (localStorage.getItem('userInfo')) {
    return JSON.parse(localStorage.getItem('userInfo'))
  }
  return ''
}

const getDefaultState = () => {
  return {
    user: getUser()
  }
}

const state = getDefaultState()

const mutations = {
  SET_USER: (state, userInfo) => {
    // console.log('mutations', userInfo)
    state.user = userInfo
  },
  RESET_STATE: (state, userInfo) => {
    state.user = ''
  }
}

const actions = {
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      login(data).then((res) => {
        if (res.code === 0) {
          // commit('USERINFO', res.data)
          // 存储到localStorage
          localStorage.setItem('userInfo', JSON.stringify(res.data))
          commit('SET_USER', res.data)
          resolve(res.data)
        }
      }).catch(() => { // 请求直接被 untils/request 拦截了
        reject()
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    commit('RESET_STATE')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

